/**
 * 
 */
package com.obradovicnjegovan.webprodavnica.pages;

import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.tynamo.security.services.SecurityService;

import com.obradovicnjegovan.webprodavnica.controller.ControllerAL;
import com.obradovicnjegovan.webprodavnica.entities.Korisnik;
import com.obradovicnjegovan.webprodavnica.entities.Narudzbenica;
import com.obradovicnjegovan.webprodavnica.entities.OdabranProizvod;

/**
 * @author njegovan
 *
 */
public class Order {
	@Inject
	private ControllerAL controllerAL;

	public Narudzbenica getNarudzbenica() {
		return controllerAL.getKorpa().getNarudzbenica();
	}
	
	public void onActivate(){
		System.out.println(getNarudzbenica());
	}
	
//	@Property
//	private String ime;
//	@Property
//	private String prezime;
//	@Property
//	private String email;
//	@Property
//	private String telefon;
	@Property
	private String adresa;
	@Property
	private String drzava;
	@Property
	private String grad;
	@Property
	private String komentar;
	@InjectComponent
	private Form potvrdiNarudzbinu;
	@InjectPage
	private Checkout checkout;
	@Inject
    private SecurityService securityService;
	
	@CommitAfter
	public Object onSubmitFromPotvrdiNarudzbinu(){
		Korisnik k = controllerAL.pronadjiKoriznika(securityService.getSubject().getPrincipal());
		k.setKorpa(getNarudzbenica().getKorpa());
		getNarudzbenica().setAdresa(adresa);
		getNarudzbenica().setGrad(grad);
		getNarudzbenica().setKomentar(komentar);
		getNarudzbenica().setKorisnik(k);
		getNarudzbenica().getKorpa().setUkupnaCena(getUkupnaCena());
		checkout.setNarudzbenica(getNarudzbenica());
		return checkout;
	}
	
	@Property
	private OdabranProizvod op;
	public String formatCena(double cena){
		return controllerAL.formatDouble(cena);
	}
	
	public double getCenaOd(){
		return op.getProizvod().getCena()*op.getKolicina();
	}
	
	public double getUkupnaCena(){
		double ukupnaCena = 0;
		try {
			for (OdabranProizvod od : controllerAL.getKorpa().getOdabraniProizvodi()) {
				ukupnaCena = ukupnaCena + (od.getProizvod().getCena()*od.getKolicina());
			}
			return  ukupnaCena;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}
}